<template>
    <div class="login-container">
        <el-card class="login-card">
            <h2 class="login-title">后台管理系统登录</h2>
            <el-form :model="loginForm" label-width="80px">
                <el-form-item label="手机号">
                    <el-input v-model="loginForm.phone" placeholder="请输入手机号" />
                </el-form-item>
                <el-form-item label="密码">
                    <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" />
                </el-form-item>
                <el-form-item label="验证码">
                    <el-input v-model="code" placeholder="请输入验证码" />
                    <div style="font-size:24px;cursor:pointer;" @click="refrenseCode()">{{ captcha }} </div>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleLogin">登录</el-button>
                    <el-button type="info" @click="handleReset">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import type { AdminLoginVO } from '../type'
import { login } from '../api/admin';
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { useAdminStore } from '../store/index'
import { generateCode } from '../api/sys';

const router = useRouter()
const adminStore = useAdminStore()

const loginForm = reactive<AdminLoginVO>({
    phone: '888',
    password: 'admin'
});

const code = ref("");

const captcha = ref("");

const refrenseCode = function () {
    generateCode().then((code) => {
        captcha.value = code;
    })
}


const handleLogin = () => {
    if (!loginForm.phone || !loginForm.password) {
        ElMessage.error('账号和密码不能为空')
        return
    }

    // 这里可以添加登录逻辑
    login(loginForm, code.value).then((admin) => {
        // 调用状态管理的 API 
        adminStore.setAdmin(admin);
        // 跳转到 index  
        router.push('/index')
    }).catch(error => {
        ElMessage.error(error)
    })
}

const handleReset = () => {
    // 这里可以添加重置密码逻辑
    loginForm.phone = '';
    loginForm.password = '';
}

onMounted(() => {
    // 获取验证码
    generateCode().then((code) => {
        captcha.value = code;
    })
})

</script>

<style scoped>
.login-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-image: url('https://img1.baidu.com/it/u=1546635205,2862421416&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=281');
    background-size: cover;
    background-position: center;
}

.login-card {
    width: 400px;
    padding: 20px;
    background-color: rgba(255, 255, 255, 0.9);
}

.login-title {
    text-align: center;
    margin-bottom: 20px;
}

.el-button--text {
    color: #409eff;
    padding: 0;
}

.el-button--text:hover {
    color: #66b1ff;
    text-decoration: underline;
}
</style>
